package com.util;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

import com.config.ConstDefine;


@Component
public class CookieUtil {

	@Resource
	HttpServletRequest request;
	@Resource
	HttpServletResponse response;
	
	/**
	 * 新增KOOKIE
	 * @param name
	 * @param value
	 * @param times
	 * @param path
	 */
	public void setCookie(String name,String value,int times)
	{
		 Cookie cookie = new Cookie(name.trim(), value.trim());
         cookie.setMaxAge(times);// 设置超时时间
         cookie.setPath(ConstDefine.cookiePath);
//         System.out.println("已添加===============");
         response.addCookie(cookie);
	}
	/**
	 * 读取COOCIE
	 * @param name
	 * @return
	 */
	public String getCookie(String name)
	{
		String res="";
		Cookie[] cookies = request.getCookies();  
        if(null!=cookies){  
            for(Cookie cookie : cookies){  
                if(cookie.getName().equals(name))
                {
                	res=cookie.getValue();
                	break;
                }
                
            }  
        }  
        return res;
	}
	/**
	 * 删除COOKIE
	 * @param name
	 */
	public void delCookies(String name)
	{
		Cookie[] cookies = request.getCookies();  
        if(null!=cookies){  
            for(Cookie cookie : cookies){  
                if(cookie.getName().equals(name))
                {
                	cookie.setValue(null);
                	cookie.setMaxAge(0);
                	cookie.setPath(ConstDefine.cookiePath);
                	response.addCookie(cookie);
                	break;
                }
                
            }  
        }  
	}
	
}
